package cn.dglydrpy.study.mmail.product.service.impl;

import cn.dglydrpy.study.mmail.common.dto.SkuRedutionDTO;
import cn.dglydrpy.study.mmail.common.dto.SpuBoundsDTO;
import cn.dglydrpy.study.mmail.common.utils.R;
import cn.dglydrpy.study.mmail.product.entity.*;
import cn.dglydrpy.study.mmail.product.feign.CouponFeignService;
import cn.dglydrpy.study.mmail.product.service.*;
import cn.dglydrpy.study.mmail.product.vo.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.dglydrpy.study.mmail.common.utils.PageUtils;
import cn.dglydrpy.study.mmail.common.utils.Query;

import cn.dglydrpy.study.mmail.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    
    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;


    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;
    
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;
    
    
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存商品的上架信息
     * @param spuInfoVO
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuInfoVO spuInfoVO) {
        // pms_spu_info 保存spu基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVO, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        spuInfoEntity.setPublishStatus(0); // 默认 "新建"  0-新建 1-上架 2-下架
        this.save(spuInfoEntity);
        
        // pms_spu_info_desc 保存spu的描述信息
        List<String> decripts = spuInfoVO.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decripts));
        spuInfoDescService.save(spuInfoDescEntity);
        
        // pms_spu_images 保存spu的图集
        List<String> images = spuInfoVO.getImages();
        List<SpuImagesEntity> spuImagesEntities = images.stream().map(item -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setSpuId(spuInfoEntity.getId());
            spuImagesEntity.setImgUrl(item);
            return spuImagesEntity;
        })
//                .filter(img -> {return img.getDefaultImg() == 1;})
                .collect(Collectors.toList());
        spuImagesService.saveBatch(spuImagesEntities);
        
        // pms_product_attr_value 保存spu的规格参数（销售属性）
        List<BaseAttrs> baseAttrs = spuInfoVO.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrs =  baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrs);
        
        List<Skus> skus = spuInfoVO.getSkus();
        if(skus != null && skus.size() > 0){
            skus.forEach((item) ->{
                // 保存当前spu对应的所有sku信息  pms_sku_info 
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0L);
                List<Images> images1 = item.getImages();
                if(images1 != null && images1.size() > 0){
                    String defaultImg = "";
                    for (Images image : images1) {
                        if(image.getDefaultImg() == 1){
                            defaultImg = image.getImgUrl();
                        }
                    }
                    skuInfoEntity.setSkuDefaultImg(defaultImg);
                }
                skuInfoService.save(skuInfoEntity);

                // pms_sku_image
                List<SkuImagesEntity> skuImages =  images1.stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImages);

                // 折扣、减满信息(sms_sku_ladder sms_full_reduction)、会员价(sms_member_price) 
                SkuRedutionDTO skuRedutionDTO = new SkuRedutionDTO();
                BeanUtils.copyProperties(item,skuRedutionDTO);
                
                // 设置会员价
                if(item.getMemberPrice() != null && item.getMemberPrice().size() > 0){
                    
                    List<cn.dglydrpy.study.mmail.common.dto.MemberPrice> memberPrices = item.getMemberPrice().stream().map(memberPrice -> {
                        cn.dglydrpy.study.mmail.common.dto.MemberPrice memberPrice1 = new cn.dglydrpy.study.mmail.common.dto.MemberPrice();
                        BeanUtils.copyProperties(memberPrice, memberPrice1);
                        return memberPrice1;
                    }).collect(Collectors.toList());
                    
                    skuRedutionDTO.setMemberPrice(memberPrices);
                }
                
                skuRedutionDTO.setSkuId(skuInfoEntity.getSkuId());
                R r = couponFeignService.saveFullRedution(skuRedutionDTO);
                if(r.getCode() != 0){
                    log.error("远程调用coupon服务,满减会员价信息处理失败！");
                }

                // pms_sku_sale_attr_value
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = item.getAttr().stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr,skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                
            });
        }



        // sms_spu_bounds 保存spu的积分信息 
        Bounds bounds = spuInfoVO.getBounds();
        SpuBoundsDTO spuBoundsDTO = new SpuBoundsDTO();
        spuBoundsDTO.setSpuId(spuInfoEntity.getId());
        spuBoundsDTO.setBuyBounds(bounds.getBuyBounds());
        spuBoundsDTO.setGrowBounds(bounds.getGrowBounds());
        R r = couponFeignService.saveSpuBounds(spuBoundsDTO);
        if(r.getCode() != 0){
            log.error("远程调用coupon服务,保存积分信息处理失败！");
        }


    }

    /**
     * SPU信息分页组合检索
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> spuInfoEntityQueryWrapper = new QueryWrapper<>();
        
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            spuInfoEntityQueryWrapper.and((wrapper) -> {
                wrapper.eq("id",key)
                        .or().like("spu_name",key)
                        .or().like("spu_description",key);
            });
        }
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            spuInfoEntityQueryWrapper.eq("publish_status",status);
        }
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            spuInfoEntityQueryWrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            spuInfoEntityQueryWrapper.eq("catalog_id",catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                spuInfoEntityQueryWrapper
        );


        List<SpuInfoVO> list = page.getRecords().stream().map(item -> {

            SpuInfoVO spuInfoVO = new SpuInfoVO();
            BeanUtils.copyProperties(item,spuInfoVO);
            spuInfoVO.setBrandName(brandService.getById(item.getBrandId()).getName());
            spuInfoVO.setCatelogName(categoryService.getById(item.getCatalogId()).getName());
            
            return spuInfoVO;
        }).collect(Collectors.toList());

        IPage<SpuInfoVO> rePage = new Page<>();
        rePage.setRecords(list);
        rePage.setPages(page.getPages());
        rePage.setCurrent(page.getCurrent());
        return new PageUtils(rePage);
    }

}
